package com.ztesoft.sca.thread;

import com.ztesoft.sca.controller.V3ToWav;
import com.ztesoft.sca.dao.ThreadManageDao;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Map;

@Service
public class IvrConvert {
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private ThreadManageDao tmDao;
    private FTPClient ftpClient;

    public Map convert(Map order) throws Exception {
        logger.info("Task1 started.");
        long start = System.currentTimeMillis();
        FileOutputStream fos = null;
        FileInputStream fis= null;

        try {

            //ivr下载地址
            Map dlFtpPath = tmDao.qryOsPublic("IVR_VOICE_PATH_DOWNLOAD",null);
            //本机储存地址
            Map localPathMap = tmDao.qryOsPublic("IVR_LOCAL_VOICE_PATH",null);
            //上传地址
            Map ulFtpPath = tmDao.qryOsPublic("IVR_VOICE_PATH_UPLOAD",null);

            if (null == dlFtpPath || "".equals(dlFtpPath)) {
                throw new Exception("ftp文件路径为空!");
            }
            int port = 21;


            String path =MapUtils.getString(order, "file_path");
            String localSavePath=MapUtils.getString(localPathMap, "CODEA")+path.substring(0,path.length()-3)+"wav";
            //下载


//			// 配置代理ftp地址就用代理地址
//			if (null != ftpProxy && !"".equals(ftpProxy)) {
//				ip = ftpProxy;
//			}
            /************************下载开始 ********************************/
            String dlUserName = MapUtils.getString(dlFtpPath, "CODEC");
            String dlPassword = MapUtils.getString(dlFtpPath, "CODED");
            String dlIp = MapUtils.getString(dlFtpPath, "CODEA");
            logger.debug("----下载ftp: username=" + dlUserName + ",password=" + dlPassword + ",ip=" + dlIp + ",port=" + port);

            // 登录
            loginFtp(dlUserName, dlPassword, dlIp, port);

            File localFile = new File(localSavePath);
            if(!localFile.getParentFile().exists()){
                logger.info("=======本地目录不存在，创建目录=========");
                localFile.getParentFile().mkdirs();
            }

            fos = new FileOutputStream(localSavePath);
            logger.debug("===========remoteFileName:" + path);
            logger.debug("===========localPath:" + localSavePath);

            getFtpClient().retrieveFile(new String(path.getBytes("GBK"), "ISO-8859-1"), fos);
            fos.flush();
            fos.close();
            logger.debug("===========获取完毕");


            /************************下载结束 ********************************/



            /************************转换开始 ********************************/
            //转码
            localSavePath=V3ToWav.voxConvert(localSavePath, null, 1, 6000, 1);
            logger.debug("===========转码完毕" + localSavePath);

            /************************转换开始 ********************************/


            /************************上传开始 ********************************/

            String ulUserName = MapUtils.getString(ulFtpPath, "CODEC");
            String ulPassword = MapUtils.getString(ulFtpPath, "CODED");
            String ulIp = MapUtils.getString(ulFtpPath, "CODEA");
            logger.debug("----上传ftp: username=" + ulUserName + ",password=" + ulPassword + ",ip=" + ulIp + ",port=" + port);

            closeFtp();

            loginFtp(ulUserName, ulPassword, ulIp, port);

            if(!getFtpClient().changeWorkingDirectory(new String(localSavePath.getBytes("GBK"), "ISO-8859-1"))){
                getFtpClient().makeDirectory(new String(localSavePath.getBytes("GBK"), "ISO-8859-1"));
                getFtpClient().changeWorkingDirectory(new String(localSavePath.getBytes("GBK"), "ISO-8859-1"));
            }

            fis= new FileInputStream(localSavePath);
            getFtpClient().setFileType(FTP.BINARY_FILE_TYPE);
            getFtpClient().setDataTimeout(30000);
            getFtpClient().storeFile(localSavePath, fis);
            logger.debug("===========上传完毕");
            /************************上传结束 ********************************/

            try{
                localFile.delete();
                logger.debug("===========删除零时文件完成");
            }catch(Exception e){
                logger.error("删除零时文件失败! 文件：" + localSavePath, e);
                e.printStackTrace();
            }

            String fileName=MapUtils.getString(order, "file_name");
            order.put("file_path", localSavePath);
            order.put("file_name", fileName.substring(0,path.length()-3)+"wav");

            order.put("serverIp",ulIp);
            order.put("serverName",ulUserName);
            order.put("serverPassword",ulPassword);

        } catch (Exception e) {
            logger.error("转换文件失败! 文件：" , e);
            e.printStackTrace();
            throw new Exception("转换文件异常," + e.getMessage());
        } finally {
            try{
                IOUtils.closeQuietly(fos);
            }catch(Exception e){
                e.printStackTrace();
            }
            try{
                IOUtils.closeQuietly(fis);
            }catch(Exception e){
                e.printStackTrace();
            }
            try{
                // 登出
                closeFtp();
            }catch(Exception e){
                e.printStackTrace();
            }
        }

        long end = System.currentTimeMillis();

        logger.info("Task1 finished, time elapsed: {} ms.", end-start);
        return order;

    }

    private void loginFtp(String userName, String password, String ip, int port) throws IOException {
        getFtpClient().setDefaultTimeout(1000 * 30);
        getFtpClient().setDefaultPort(port);
        getFtpClient().connect(ip);
        getFtpClient().login(userName, password);
        getFtpClient().enterLocalPassiveMode();
    }

    private void closeFtp() throws IOException {
        try{
            getFtpClient().logout();
        }catch(Exception e){
            e.printStackTrace();
        }
        try{
            getFtpClient().disconnect();
        }catch(Exception e){
            e.printStackTrace();
        }
        ftpClient = null;
    }

    private FTPClient getFtpClient() {
        if (null == ftpClient) {
            ftpClient = new FTPClient();
        }
        return ftpClient;
    }
}
